package com.alianzamedica.controllers.patient;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.objectsearch.sqlsearch.ObjectSearch;
import org.w3c.dom.Document;

import com.alianzamedica.businessobject.Patient;
import com.alianzamedica.controllers.constants.ActionConstants;
import com.alianzamedica.tools.Enviroment;

/**
 * @author Carlos
 * 
 */
public class PatientListAction extends Action {

	@SuppressWarnings("unchecked")
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		Enviroment env = Enviroment.getInstance();
		Document doc = env.getDocument();
		ObjectSearch search = new ObjectSearch(doc,
				"com.alianzamedica.connection.ConnectionImpl");
		search.setDefaultDialect(ObjectSearch.MYSQL_DIALECT);
		search.setLike(true);
		String patientName = request.getParameter("nombre");
		String sNumPage = request.getParameter("pageNum");
		Integer numPage = 1;
		if (sNumPage != null && sNumPage.trim().length() > 0) {
			try {
				numPage = Integer.parseInt(sNumPage);
			} catch (Exception e) {
			}
		}

		Patient p = new Patient();
		if (patientName != null && patientName.trim().length() > 0) {
			p.setFullName(patientName);
		}
		Integer totalPages = search.getTotalPages(p);
		request.setAttribute("totalPages", totalPages);
		ArrayList patients = search.getPagedQuery(p, null, numPage, ActionConstants.PAGE_SIZE);
		request.setAttribute("patients", patients);

		return mapping.findForward("success");
	}

}
